package command.server;

import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import model.MessageCommunication;
import model.User;
import persistence.UserDAO;
import persistence.ValidationMethods;
import server.ClientThread;
import server.Server;

public class CreateUserServer implements CommandServer {

    UserDAO persistenceMechanism;

    public CreateUserServer() {
    }

    @Override
    public void execute(ClientThread clientThread) {
        persistenceMechanism = Server.getServerUserDAO();
        try {
            User user = (User) clientThread.getObjectInputStream().readObject();
            ValidationMethods validation = new ValidationMethods(user);
            if (validation.validateAllMethods()) {
                if (persistenceMechanism.newUser(user)) {
                    clientThread.getObjectOutputStream().writeObject(
                            new MessageCommunication(true, "El usuario ha sido creado con éxito"));
                } else {
                    clientThread.getObjectOutputStream().writeObject(
                            new MessageCommunication(false, "El usuario que se intenta crear ya existe"));
                }
            } else {
                clientThread.getObjectOutputStream().writeObject(
                        new MessageCommunication(false, "Los datos del usuario no son válidos"));
            }
            clientThread.getObjectOutputStream().flush();
        } catch (IOException | ClassNotFoundException ex) {
            Logger.getLogger(CreateUserServer.class.getName()).log(Level.SEVERE,
                    "Hubo un problema al crear el nuevo Usuario", ex);
        }
    }
}
